package city.spring.controller.mealService;

import city.spring.domain.entity.mealService.FoodInfoEntity;
import city.spring.service.mealService.FoodInfoService;
import city.spring.utils.MyBatisUtils;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/food/{foodId}/info")
public class FoodInfoController extends ApiController {

    /**
     * <strong></strong> Service
     */
    private final FoodInfoService foodInfoService;
    /**
     * 实体类（）可排序字段
     */
    private final List<SFunction<FoodInfoEntity, ?>> entityOrderFields;

    public FoodInfoController(FoodInfoService foodInfoService) {
        this.foodInfoService = foodInfoService;
        this.entityOrderFields = new ArrayList<>();
        entityOrderFields.add(FoodInfoEntity::getId);
        entityOrderFields.add(FoodInfoEntity::getFoodId);
        entityOrderFields.add(FoodInfoEntity::getFoodName);
        entityOrderFields.add(FoodInfoEntity::getFoodPrize);
        entityOrderFields.add(FoodInfoEntity::getHot);
        entityOrderFields.add(FoodInfoEntity::getTexture);
        entityOrderFields.add(FoodInfoEntity::getTaste);
        entityOrderFields.add(FoodInfoEntity::getDistributionString);
        entityOrderFields.add(FoodInfoEntity::getStartTime);
        entityOrderFields.add(FoodInfoEntity::getEndTime);
        entityOrderFields.add(FoodInfoEntity::getProvideString);
        entityOrderFields.add(FoodInfoEntity::getRemarks);
    }

    /**
     * 获取全部的 <strong></strong> 列表
     */
    @GetMapping("all")
    public Object listAll(@PageableDefault(sort = {"gmtCreate"}) Pageable pageable, FoodInfoEntity entity) {
        LambdaQueryChainWrapper<FoodInfoEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        return success(lambdaQuery.list());
    }

    /**
     * 分页获取 <strong></strong> 列表
     *
     * @param pageable 分页参数信息
     */
    @GetMapping
    public Object list(@PageableDefault(sort = {"gmtCreate"}) Pageable pageable, FoodInfoEntity entity, @PathVariable String foodId) {
        LambdaQueryChainWrapper<FoodInfoEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        lambdaQuery.eq(FoodInfoEntity::getFoodId, foodId);
        Page<FoodInfoEntity> page = lambdaQuery.page(MyBatisUtils.toPage(pageable, false));
        for (FoodInfoEntity record : page.getRecords()) {
            try {
                if (record.isDistribution()) {
                    record.setDistributionString("可以配送");
                } else {
                    record.setDistributionString("暂时无法配送");
                }
            } catch (Exception ignore) {
                record.setDistributionString("");
            }
            try {
                if (record.isProvide()) {
                    record.setProvideString("正在供应");
                } else {
                    record.setProvideString("暂时无法供应");
                }
            } catch (Exception ignore) {
                record.setProvideString("");
            }
        }
        return success(page);
    }

    /**
     * 获取一个 <strong></strong>
     *
     * @param id 主键ID
     */
    @GetMapping("{id}")
    public Object info(@PathVariable String id) {
        FoodInfoEntity entity = foodInfoService.getById(id);
        try {
            if (entity.isDistribution()) {
                entity.setDistributionString("可以配送");
            } else {
                entity.setDistributionString("暂时无法配送");
            }
        } catch (Exception e) {
            entity.setDistributionString("暂时未知");
        }
        try {
            if (entity.isProvide()) {
                entity.setProvideString("正在供应");
            } else {
                entity.setDistributionString("暂时无法供应");
            }
        } catch (Exception e) {
            entity.setProvideString("");
        }
        foodInfoService.loadDisease(entity);
        return success(entity);
    }

    /**
     * 添加一个 <strong></strong>
     *
     * @param entity 新增的信息
     */
    @PostMapping
    public Object add(@RequestBody FoodInfoEntity entity, @PathVariable String foodId) {
        entity.setFoodId(foodId);
        foodInfoService.saveFoodInfo(entity);
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.LOCATION, entity.getId());
        return new ResponseEntity<>(headers, HttpStatus.CREATED);
    }

    /**
     * 修改一个 <strong></strong>
     *
     * @param id     主键ID
     * @param entity 修改后的信息
     */
    @PutMapping("{id}")
    public Object update(@PathVariable String id, @RequestBody FoodInfoEntity entity, @PathVariable String foodId) {
        entity.setId(id);
        entity.setFoodId(foodId);
        foodInfoService.updateFoodInfo(entity);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 删除一个 <strong></strong>
     *
     * @param id 主键ID
     */
    @DeleteMapping("{id}")
    public Object delete(@PathVariable String id) {
        foodInfoService.removeById(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 删除多个 <strong></strong>
     *
     * @param ids 主键ID列表
     */
    @DeleteMapping
    public Object deleteIds(@RequestBody List<String> ids) {
        foodInfoService.removeByIds(ids);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象： <strong></strong>
     * @return lambda query chain wrapper
     */
    private LambdaQueryChainWrapper<FoodInfoEntity> buildLambdaQuery(FoodInfoEntity entity) {
        LambdaQueryChainWrapper<FoodInfoEntity> lambdaQuery = foodInfoService.lambdaQuery();
        lambdaQuery.eq(StringUtils.isNotBlank(entity.getId()), FoodInfoEntity::getId, entity.getId());
        lambdaQuery.eq(StringUtils.isNotBlank(entity.getFoodName()), FoodInfoEntity::getFoodName, entity.getFoodName());
        return lambdaQuery;
    }

}
